package com.daguchuangyi.erp_android.manager;

import com.daguchuangyi.erp_android.manager.database.UserInfoTable;
import com.daguchuangyi.erp_android.model.account.UserInfoModel;
import com.raizlabs.android.dbflow.sql.language.SQLite;

import java.util.List;

/**
 * Created by lijianjian on 2018/3/17.
 */

public class UserInfoManager {
    private static final String USER_INFO_TAG = "USER_INFO_TAG";
    private static UserInfoManager sUserInfoManager;

    private UserInfoModel mUserInfoModel;

    public static synchronized UserInfoManager getUserInfoManager() {
        if (sUserInfoManager == null) {
            synchronized (UserInfoManager.class) {
                sUserInfoManager = new UserInfoManager();
            }
        }
        return sUserInfoManager;
    }

    private UserInfoManager() {
    }

    public String getToken() {
        UserInfoModel userInfoModel = getUserInfoModel();
        if (userInfoModel != null) {
            return mUserInfoModel.getUser().getToken();
        } else {
            return "";
        }
    }

    public UserInfoModel getUserInfoModel() {
        if (mUserInfoModel == null) {
            List<UserInfoTable> userInfoTables = SQLite.select().from(UserInfoTable.class).queryList();
            if (userInfoTables.size() != 0) {
                UserInfoTable userInfoTable = userInfoTables.get(userInfoTables.size() - 1);
                mUserInfoModel = new UserInfoModel();
                UserInfoModel.User user = new UserInfoModel.User();
                user.setAvatar(userInfoTable.avatarUrl);
                user.setToken(userInfoTable.token);
                user.setId(userInfoTable.id);
                user.setType(userInfoTable.type);
                user.setName(userInfoTable.name);
                mUserInfoModel.setUser(user);
            }
        }
//        if (mUserInfoModel == null) {
//            return "";
//        } else {
//            return mUserInfoModel.getUser().getToken();
//        }
        return mUserInfoModel;
    }

    public void setUserInfoModel(UserInfoModel userInfoModel) {
        mUserInfoModel = userInfoModel;
        UserInfoTable userInfoTable = new UserInfoTable();
        userInfoTable.id = userInfoModel.getUser().getId();
        userInfoTable.avatarUrl = userInfoModel.getUser().avatar;
        userInfoTable.name = userInfoModel.getUser().getName();
        userInfoTable.token = userInfoModel.getUser().getToken();
        userInfoTable.type = userInfoModel.getUser().getType();
        userInfoTable.save();
    }
}
